package com.abc.robot01.vivemodel

import android.util.Log
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.abc.robot01.retrofit.RetrofitService
import com.abc.robot01.retrofit.bean.DataB
import com.abc.robot01.retrofit.bean.FetchDataRequest2
import com.abc.robot01.retrofit.bean.HouseType
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class ShangPinKuViewModel : ViewModel() {

    val TAG = "ShangPinKuViewmodel"

    val showPopup =  mutableStateOf(false)

    // MutableStateFlow 用来保存当前的列表状态
    private val _questionList = MutableStateFlow<List<DataB>>(emptyList())
    val dataList: StateFlow<List<DataB>> = _questionList

    val name = mutableStateOf("")

    var isToggled = mutableStateOf(true)

    //喜好
    private val _question2List = MutableStateFlow<List<HouseType>>(mutableListOf(HouseType()))
    val question2List: StateFlow<List<HouseType>> = _question2List

    //墙体类型
    private val _question3List = MutableStateFlow<List<HouseType>>(mutableListOf(HouseType()))
    val question3List: StateFlow<List<HouseType>> = _question3List

    val interestsCode = mutableStateOf("")
    val interests = mutableStateOf("全部")

    // 模拟网络分批返回数据的函数

    val pageSize = 100;

    //默认价格降序
    fun loadMoreData(
        orderBy: String = if (isToggled.value) "price asc" else "price desc",
        name: String = "",
        interest: String = interestsCode.value
    ) {
        viewModelScope.launch(IO) {
            Log.e(TAG, "start loadMoreData,name:$name");
            Log.e(TAG, "商品库,名称:$name,喜欢:" + interest);
            _questionList.value = emptyList()
            repeat(10000) {
                val newBatch = fetchNextBatchFromNetwork(
                    name,
                    offset = pageSize * it,
                    fetchSize = pageSize,
                    orderBy = orderBy,
                    interest = interest
                )
                if (newBatch.first.isEmpty()) return@launch
                _questionList.value += newBatch.first
                if (newBatch.second == _questionList.value.size) {
                    Log.e(TAG, "last data ,total  ${newBatch.second}");
                    return@launch
                }
            }
        }
    }

    // 模拟获取网络数据的方法
    private suspend fun fetchNextBatchFromNetwork(
        name: String,
        interest: String,
        offset: Int,
        fetchSize: Int,
        orderBy: String
    ): Pair<List<DataB>, Int> {
        val data = mutableListOf<DataB>()
        val result = RetrofitService.instance.getCompanyProduct(
            userId = Robot.userId, companyId = Robot.companyId,
            FetchDataRequest2(
                offset = offset,
                fetchSize = fetchSize,
                orderBy = orderBy,
                name = name,
                interest = interest
            )
        )
//        Log.e(TAG, "userId ${Robot.userId}");
//        Log.e(TAG, "companyId ${Robot.companyId}");
//        Log.e(TAG, "fetchNextBatchFromNetwork: $result");
        if (result.code == 200) {
            result.data.list.forEach {
//                Log.e(TAG, "commodity item : ${it}");
                data.add(
                    DataB(
                        unitName=it.unitName,
                        id = it.id,
                        name = it.name,
                        price = "${it.price}",
                        thumbnail = it.thumbnail
                    )
                )
            }
        }
//        Log.e(TAG, "fetchNextBatchFromNetwork, data.size: ${data.size}");
        // 返回一些新数据
        return data to result.data.total
    }

    init {
        loadMoreData()
        loadData2()
    }

    private fun loadData2() {
        //喜好
        viewModelScope.launch {
            Log.e(TAG, "喜好")

            val s = RetrofitService.instance.getSysDicByType(
                accessToken = Robot.accessToken,
                type = "INTEREST"
            )
            _question2List.value = mutableListOf(HouseType())
            _question2List.value += s.data
            Log.e(TAG, "喜好:$s")

            val s2 = RetrofitService.instance.getSysDicByType(
                accessToken = Robot.accessToken,
                type = "WALL_TYPE"
            )
            _question3List.value = s2.data
            Log.e(TAG, "墙体类型:$s2")
        }
    }
}


